using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DaprPlus.Dapr;

public static class DaprExtensions
{
    public static HttpRequestMessage CreateInvokeMethodRequest(this IServiceProvider serviceProvider, HttpMethod method, string appId, string methodName)
    {
        var token = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext?.Request.Headers.Authorization.ToString();
        var daprClient = serviceProvider.GetRequiredService<DaprClient>();
        var request = daprClient.CreateInvokeMethodRequest(method, appId, methodName);
        if (!string.IsNullOrEmpty(token))
        {
            request.Headers.Add("Authorization", token);
        }
        return request;
    }

    public static HttpRequestMessage CreateInvokeMethodRequest<TRequest>(this IServiceProvider serviceProvider, string appId, string methodName, TRequest data)
    {
        var token = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext?.Request.Headers.Authorization.ToString();
        var daprClient = serviceProvider.GetRequiredService<DaprClient>();
        var requestMessage = daprClient.CreateInvokeMethodRequest(HttpMethod.Post, appId, methodName, new List<KeyValuePair<string, string>>(), data);
        if (!string.IsNullOrEmpty(token))
        {
            requestMessage.Headers.Add("Authorization", token);
        }
        return requestMessage;
    }

    public static HttpRequestMessage CreateInvokeMethodRequest<TRequest>(this IServiceProvider serviceProvider, HttpMethod method, string appId, string methodName, TRequest data)
    {
        var token = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext?.Request.Headers.Authorization.ToString();
        var daprClient = serviceProvider.GetRequiredService<DaprClient>();
        var requestMessage = daprClient.CreateInvokeMethodRequest(method, appId, methodName, new List<KeyValuePair<string, string>>(), data);
        if (!string.IsNullOrEmpty(token))
        {
            requestMessage.Headers.Add("Authorization", token);
        }
        return requestMessage;
    }
}

